package cn.jiedh.app.meiweidk.homepage;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.xutils.ex.HttpException;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.MyWebActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.GreenDialog;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.interfaces.onLoadFinishListener;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.DeviceUtils;
import cn.jiedh.app.meiweidk.Utils.tool.JsonUtil;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.mine.AuthenActivity;
import cn.jiedh.app.meiweidk.mine.PersonInfo;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.web.WebActivity;

/**
 * @name：
 * @author：彭鑫
 * @phone：18423134135
 * @createTime：2017/10/20
 */

public class  GreenLandActivity extends BaseActivity {

    private Dialog dialog;

    private GreenDialog loadingDialog;


    @BindView(R.id.tips_tv)
    TextView tips_tv;//剩余次数

    @Override
    protected int getLayoutView() {
        return R.layout.activity_green_land;
    }

    @Override
    protected void initView(View view) {
        setTitle(" ");
    }

    @Override
    protected void initData() {
        loadingDialog = new GreenDialog(this);
        loadingDialog.setFinishListener(() -> {
            loadingDialog.dismiss();
            sendProductRequest();
        });

        sendTipsRequest();
    }


    /**
     * 当前剩余多少次
     */
    private void sendTipsRequest() {
        showLoadingDialog();

        Map<String, Object> map = new HashMap<>();

        request(UrlUtils.GREEN_LAND_LIMIT, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse<String> response) {
                dismissLoadingDialog();
                if (response.getCode() == 0) {//剩余1次
                    tips_tv.setText("1");
                } else {
                    tips_tv.setText("0");
                }

            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                dismissLoadingDialog();
                tips_tv.setText("0");
            }
        });
    }


    /**
     * 获取当前用户认证信息
     */
    private void sendGetData() {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();

        request(UrlUtils.GREEN_LAND_DATA, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse<String> response) {
                dismissLoadingDialog();
                if (response.getCode() == 0) {//个人资料已完善

                    //如果没有用户信息就请求并且保存
                    if(StringUtil.isEmpty(SPUtils.getValue(ConfigUtils.USER_IDCARD))){
                        getPersonData();
                    }else{
                        initDialog();
                    }


                } else {//个人资料未完善 跳转到完善个人资料
                    AlertDialog dialog = new AlertDialog(GreenLandActivity.this).builder();

                    dialog.setMsg("您还未实名认证，请先通过实名认证").setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ActivityUtil.next(GreenLandActivity.this, AuthenActivity.class);
                        }
                    }).show();


                }

            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                dismissLoadingDialog();
//                tips_tv.setText("0");
            }
        });
    }



    /**
     * 获取用户信息
     */
    private void getPersonData() {
        Map<String, Object> args = new HashMap<>();
        args.put("phone", SPUtils.getPhone());
        request(this, UrlUtils.GET_PERSONAL_INFO, args, true, new ResponseSuccess<PersonInfo>() {
            @Override
            public void onRequestSucceed(BaseResponse<PersonInfo> response) {
                PersonInfo infor = response.getData();
                if (response.isSuccess()) {
                    SPUtils.saveUserData(infor);
                    initDialog();
                }
            }
        });
    }

    TextView send_code_tv;//发送验证码
    TextView check_ok;//确定
    TextView check_cancel;//取消
    TextView username_tv;
    TextView city_tv;
    TextView idcard_tv;
    TextView phone_tv;
    EditText code_et;

    DialogClick dialogClick = new DialogClick();

    /**
     * 初始化身份确认dialog
     */
    private void initDialog() {
        if (dialog == null) {
            dialog = new Dialog(this);
            dialog.setContentView(R.layout.green_check_dialog);
            send_code_tv = dialog.findViewById(R.id.send_code_tv);
            send_code_tv.setOnClickListener(dialogClick);
            check_ok = dialog.findViewById(R.id.check_ok);
            check_ok.setOnClickListener(dialogClick);
            check_cancel = dialog.findViewById(R.id.check_cancel);
            check_cancel.setOnClickListener(dialogClick);
            code_et = dialog.findViewById(R.id.code_et);

            username_tv = dialog.findViewById(R.id.username_tv);
            username_tv.setText("姓名: " + SPUtils.getValue(ConfigUtils.USER_NAME));
            city_tv = dialog.findViewById(R.id.city_tv);
            city_tv.setText("城市: " + SPUtils.getValue(ConfigUtils.USER_CITY));
            idcard_tv = dialog.findViewById(R.id.idcard_tv);
            idcard_tv.setText("身份证号码: " + SPUtils.getValue(ConfigUtils.USER_IDCARD).replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1****$2"));
            phone_tv = dialog.findViewById(R.id.phone_tv);
            phone_tv.setText(SPUtils.getPhone().substring(0, 3) + "****" + SPUtils.getPhone().substring(7, SPUtils.getPhone().length()));
            dialog.setCanceledOnTouchOutside(false);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            sendCodeRequest();
        }
        dialog.show();
    }


    /**
     * 发送验证码
     */
    private void sendCodeRequest() {
//        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", SPUtils.getPhone());

        //map.put("imgKey", imgKey);
        //map.put("imgCode", imageCodeEdt.getText().toString());
        request(UrlUtils.LOGINSMSCODE, map, true, response -> {
            dismissLoadingDialog();

            if (0 == response.getCode()) {
                T.showShort("发送成功");
                send_code_tv.setEnabled(false);
                timer.start();
            }

            if (0 != response.getCode()) {
                T.showShort(response.getMessage());
            }
        });
    }


    /**
     * 获取随机产品
     */
    private void sendProductRequest() {
        Map<String, Object> map = new HashMap<>();
        request(UrlUtils.GREEN_LAND_PRODUCT, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse<String> response) {
                if (response.getCode() == 0) {
                    String URL = JsonUtil.getJsonObjectValue(response.getData(), "adverUrl", String.class);
                    goLoadPageActivity(URL);
                    finish();
                } else {
                    T.show(response.getMessage());
                }
            }
        });
    }

    /**
     * 验证验证码是否正确
     */
    private void sendCodeAuthif(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("phone", SPUtils.getPhone());
        map.put("authCodePage", code);

        request(UrlUtils.CODE_AUTH_IF, map, true, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse<String> response) {
                if (response.getCode() == 0) {
                    loadingDialog.show();
                    loadingDialog.startStage();
                    dialog.dismiss();
                } else {
                    T.show(response.getMessage());
                }
            }
        });

    }

    /**
     * 跳转到产品H5
     */
    private void goLoadPageActivity(String applyUrl) {
        Bundle bundle = new Bundle();
        bundle.putString("url", applyUrl);
        bundle.putString("title", "推荐产品");
        Intent intent = new Intent(this, MyWebActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 发送验证码倒计时
     */
    private CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            String str = "<font color='#F5A623'>" + millisUntilFinished / 1000 + "秒</font>后重新发送";
            send_code_tv.setText(Html.fromHtml(str));
        }

        @Override
        public void onFinish() {
            send_code_tv.setEnabled(true);
            send_code_tv.setText("重新发送验证码");
        }
    };

    class DialogClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.send_code_tv://发送验证码
                    sendCodeRequest();
                    break;
                case R.id.check_ok:
                    if (!StringUtil.isEmpty(code_et.getText().toString())) {
                        sendCodeAuthif(code_et.getText().toString());
                    }else{
                        T.show("请输入验证码");
                    }
                    break;
                case R.id.check_cancel:
                    dialog.dismiss();
                    break;
            }
        }
    }

    @OnClick({R.id.get_now})
    public void Click(View v) {
        switch (v.getId()) {
            case R.id.get_now:
                if (tips_tv.getText().toString().equals("1")) {
                    sendGetData();
                } else {
                    T.show("今日次数已用完");
                }

                break;
        }
    }
}
